<template>
  <div class="main">
    <div class="air-column">
      <h2>剩机人</h2>
      <el-form
        class="member-info"
        :model="{ users }"
        ref="usersForm"
      >
        <div
          class="member-info-item"
          v-for="(item, index) in users"
          :key="index"
        >
          <el-form-item
            label="乘机人类型"
            :rules="[
              { required: true, message: '请输入乘机人的名字', trigger: 'blur' }
            ]"
            :prop="`users[${index}].username`"
          >
            <el-input
              placeholder="姓名"
              class="input-with-select"
              v-model="item.username"
              @focus="clearUserRules(`users[${index}].name`)"
            >
              <el-select
                slot="prepend"
                value="1"
                placeholder="请选择"
              >
                <el-option
                  label="成人"
                  value="1"
                ></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <el-form-item
            label="证件类型"
            :rules="[
              { required: true, message: '请输入证件号码', trigger: 'blur' }
            ]"
            :prop="`users[${index}].id`"
          >
            <el-input
              placeholder="证件号码"
              class="input-with-select"
              v-model="item.id"
              @focus="clearUserRules(`users[${index}].id`)"
            >
              <el-select
                slot="prepend"
                value="1"
                placeholder="请选择"
              >
                <el-option
                  label="身份证"
                  value="1"
                  :checked="true"
                ></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <span
            class="delete-user"
            @click="handleDeleteUser(index)"
          >-</span>
        </div>
      </el-form>

      <el-button
        class="add-member"
        type="primary"
        @click="handleAddUsers"
      >添加乘机人</el-button>
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <el-checkbox-group v-model="insurances">
        <div
          class="insurance-item"
          v-for="item in data.insurances"
          :key="item.id"
        >
          <el-checkbox
            :label="item.id"
            border
          >
            {{ item.type }}: ￥{{ item.price }} / 份 X
            {{ users.length }} 最高赔付 {{ item.compensation }}
          </el-checkbox>
        </div>
      </el-checkbox-group>
      <h2>发票</h2>
      <el-checkbox
        v-model="invoice"
        @click="invoice = !invoice"
      >申请发票</el-checkbox>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          label-width="80px"
          :model="{ contactName, contactPhone, captcha }"
          :rules="rules"
          ref="contactForm"
        >
          <el-form-item
            label="姓名"
            prop="contactName"
          >
            <el-input
              placeholder="请输入联系人"
              v-model="contactName"
              @focus="clearContactRules('contactName')"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="手机"
            prop="contactPhone"
          >
            <el-input
              placeholder="请输入手机号码"
              v-model="contactPhone"
              @focus="clearContactRules('contactPhone')"
            >
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item
            label="验证码"
            prop="captcha"
          >
            <el-input v-model="captcha"></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="warning"
          class="submit"
          @click="handleSubmit"
        >提交订单</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { sendAir } from "@/api/air";
import { sendCaptcha } from "@/api/user";
export default {
  props: {
    // 接收机票信息
    data: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      rules: {
        contactName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        contactPhone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      users: [
        {
          username: "大陆",
          id: "442551199555555555",
        },
      ],
      insurances: [], // 保险数据
      contactName: "大陆", // 联系人名字
      contactPhone: "15365478523", // 联系人电话
      captcha: "000000", // 验证码
      invoice: false, // 发票
    };
  },
  created() {
    this.calcTotalPrice();
  },
  watch: {
    users: {
      handler() {
        this.calcTotalPrice();
      },
      immediate: true,
    },
    insurances() {
      this.calcTotalPrice();
    },
  },
  methods: {
    // 计算价格
    calcTotalPrice() {
      let res = 0;
      // 1. 机票价格
      res += this.data.base_price * this.users.length;
      // 2. 保险价格

      // 当前被选中的保险是 this.insurances, 需要遍历能够拿到选中的 id
      this.insurances.forEach((idSelected) => {
        // 这里拿到id 需要到原来总的保险数据中查找出对应的价格
        // 当前所有保险数据在 this.data.insurances, 可以拿到每个保险的对象
        this.data.insurances.forEach((element) => {
          if (element.id == idSelected) {
            res += element.price * this.users.length;
          }
        });
      });

      this.$emit("setTotalPrice", res);
    },
    // 清楚表单验证
    clearUserRules(v) {
      this.$refs.usersForm.clearValidate(v);
    },
    clearContactRules(v) {
      this.$refs.contactForm.clearValidate(v);
    },
    // 添加乘机人
    handleAddUsers() {
      this.users.push({
        username: "",
        id: "",
      });
    },

    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },

    // 发送手机验证码
    async handleSendCaptcha() {
      const regexp = /^1[35789]\d{9}$/;
      if (!regexp.test(this.contactPhone)) {
        return this.$message.warning("请输入正确的手机号码");
      }
      let res = await sendCaptcha(this.contactPhone);
      if (res) {
        this.$message.success("收到手机验证码：" + res.data.code);
      }
    },

    // 提交订单
    handleSubmit() {
      Promise.all([
        this.$refs.usersForm.validate(),
        this.$refs.contactForm.validate(),
      ]).then(async (res) => {
        if (res[0] && res[1]) {
          const data = {
            users: this.users,
            insurances: this.insurances,
            contactName: this.contactName,
            contactPhone: this.contactPhone,
            invoice: this.invoice,
            seat_xid: this.$route.query.seat_xid,
            air: this.$route.query.id,
            // 文档少了一个验证码需要自己加上
            captcha: this.captcha,
          };
          const token = this.$store.state.user.userInfo.token;
          this.$message({
            message: "正在生成订单！请稍等",
            type: "success",
          });
          let res = await sendAir(data, token);
          console.log(data);
          if (res) {
            this.$message({
              message: res.data.message,
              type: "success",
            });
            this.$router.push({
              path: "/air/pay",
              query: { id: res.data.data.id },
            });
          }
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 10px;
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
</style>
